package com.leyou.user.service;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.code.PasswordConfig;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.buf.UDecoder;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @package com.leyou.user.service
 * @description:
 * @author: 86157
 * @date 2019/7/6 17:12
 * @version: V1.0
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String KEY_PREFIX = "verify:code:phone";


    /**
     * 检测用户名和手机号是否重复
     *
     * @param data
     * @param type
     * @return
     */
    public Boolean checkData(String data, Integer type) {

        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        int count = userMapper.selectCount(user);
        return count == 0;
    }


    /**
     * 用户传过来的手机号，随机生成六位数验证码发给用户
     */
    public void sendCode(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            //手机号数据不对
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }

        //生成验证码
        String code = RandomStringUtils.randomNumeric(6);

        //将验证码保存至redis中
        redisTemplate.opsForValue().set((KEY_PREFIX + phone), code, 5, TimeUnit.MINUTES);

        //指定消息发送到mq
        Map<String, String> map = new HashMap<>();

        map.put("phone", phone);
        map.put("code", code);
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME, MQConstants.RoutingKey.VERIFY_CODE_KEY, map);
    }

    /**
     * 注册业务，判断用户传的用户名，密码，需要加密，验证码
     * - 1）校验短信验证码
     * - 2）对密码加密
     * - 3）写入数据库
     */
    public void register(User user, String code) {
        user.setPassword(UDecoder.URLDecode(user.getPassword()));
        //1.校验验证吗
        //1.1取出redis中验证码
        String redisCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        //1.2比较验证码
        if (!StringUtils.equals(code, redisCode)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //2.对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        //3.写入数据库
        int count = userMapper.insertSelective(user);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    /**
     * 根据用户名和密码查询用户
     *
     * @param username
     * @param password
     * @return
     */
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        User user = new User();
        user.setUsername(username);

        //根据用户名查询用户
        User result = userMapper.selectOne(user);
        if (result == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        //根据密码判断用户密码是否正确
        if (passwordEncoder.matches(password, user.getPassword())) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        return BeanHelper.copyProperties(result, UserDTO.class);
    }
}